<template>
    <div class="contextMenu-container" ref="contextmenuRef">
        <slot></slot>
        <!-- teleport标签，让div挂到body下，绝对定位 -->
        <teleport to="body">
            <!-- <transition @before-enter="handleBeforeEnter" @enter="handleEnter" @after-enter="handleAfterEnter">
                <div class="menu-part" ref="menuRef" :style="{ top: y + 'px', left: x + 'px' }" v-if="visible">
                    <ul class="menu-list">
                        <li class="menu-item" v-for="item in menu" @click="handleSelect(item)">
                            {{ item.label }}
                        </li>
                    </ul>
                </div>
            </transition> -->
            <div class="menu-part" ref="menuRef" :style="{ top: y + 'px', left: x + 'px' }" v-if="visible">
                <ul class="menu-list">
                    <li class="menu-item" v-for="item in menu" @click="handleSelect(item)">
                        {{ item.label }}
                    </li>
                </ul>
            </div>
        </teleport>
    </div>
</template>

<script setup lang="ts">
import { ContextMenuType } from "@/type/contextMenu";
import { useContextMenu } from "@/components/contextMenu/contextmenu";

defineProps<{
  menu: ContextMenuType[];
}>();

const emits = defineEmits(["select"]);

const contextmenuRef = ref<HTMLDivElement>();
const menuRef = ref<HTMLDivElement>();
const { x, y, visible } = useContextMenu(contextmenuRef, menuRef);

const handleSelect = (item: ContextMenuType) => {
  emits("select", item);
};

const handleBeforeEnter = (el: any) => {
  el.style.height = "0px";
};

const handleEnter = (el: any) => {
  el.style.height = "auto";
  const h = el.clientHeight; //获取高度
  el.style.height = "0px";

  //下一帧渲染
  requestAnimationFrame(() => {
    el.style.height = h + "px";
    el.style.transition = "0.5s";
  });
};

const handleAfterEnter = (el: any) => {
  el.style.transition = "none";
};
</script>

<style scoped lang="scss">
.menu-part {
  position: fixed;
  border: 1px solid #ccc;
  background: var(--el-bg-color);
  z-index: 3000;
  //padding: 5px 0;
  border-radius: 4px;
  font-size: 14px;
  color: var(--el-text-color-primary);
  box-shadow: 2px 2px 3px 0 rgba(0, 0, 0, 0.2);
  overflow:hidden;
  animation: scale .2s linear;

  @keyframes scale {
    0%{
        transform: scale(0);
    }
    50%{
        transform: scale(1.2);
    }
    100%{
        transform: scale(1);
    }
  }

  .menu-list {
    list-style: none;
    padding: 0;
    margin: 0;

    .menu-item {
      cursor: pointer;
      padding: 5px 10px;

      &:hover {
        background: var(--el-color-primary);
      }
    }
  }
}
</style>
